var Povertypolicy = function() {


    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();

    var memberDatalist_url = $('.memberDatalist_url').val();

    var isLoadMemberTable = false;


    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            var columns = COLUMNS;

            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                /*"columns": [
                    {
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 60px;height: 40px;"/></a>';
                        }
                    },
                    {"data": "name"},
                    {"data": "remark"},
                    {
                        //"width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';

                            return html;
                        }
                    }
                ],*/
                "columns": columns,
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    $(nRow).find('td').find('.edit-btn').attr('href', edit_url + '?id=' + aData.id);
                },
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                    var city = $('input[name=city]').val();
                    if(city){
                        //$("#city").find("option:contains('"+city+"')").attr("selected", true);
                        get_xian($("#city"));
                    }
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    var initMemberTable = function(params) {
        var table = $('#member-datatable');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: memberDatalist_url,
                    data: params
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "avatar",
                        "render": function(data, type, row, meta) {
                            return '<img src="'+data+'" style="width: 40px;height: 40px;"/>';
                        }
                    },
                    {"data": "name"},
                    /*{
                        "data": "gender",
                        "render": function(data, type, row, meta) {
                            if(data == 1){
                                return '男';
                            }else if(data == 2){
                                return '女';
                            }else{
                                return '未知';
                            }
                        }
                    },*/
                    {"data": "gender"},
                    {
                        "width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<button type="button" class="btn btn-success select-btn">选择</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": true, // 重新加载表格内容
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    if(aData['id'] == $('input[name="memberId"]').val()) {
                        $(nRow).find(".select-btn").attr('style','background:#5cb85c');
                        $(nRow).find(".select-btn").find('input').prop('checked',true);
                    }
                },
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });

            isLoadMemberTable = true;
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 选择
        table.on('click', '.select-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var name = dataArr[0].name;

            $('input[name=memberId]').val(id);
            $('.select-member').empty().html(name);
            $('#member-modal').modal('hide');
        });
    };

    var viewMember = function () {
        var householderId = $('input[name=householderId]').val();
        if(householderId == '' || householderId == 0){
            layer.msg('请选择户主');
            return;
        }
        var params = {
            'householderId' : householderId
        };

        $('#member-modal').modal('show');
        initMemberTable(params);
    };

    // 详情页初始化
    var initDetail = function() {
        if($('#ajax-form').length > 0){
            init_specType();
            handlePolicySpec();
        }
    };

    // 初始化 享受政策规格类型
    var init_specType = function() {
        //
    };

    // 享受政策规格
    var handlePolicySpec = function() {
        $('#policy-group').find('.policy-div').each(function (i) {
            $(this).find('.policySpec-div').each(function(j){
                // $(this).find('input[name^=specType]').attr('name', 'specType_'+i);
                // $(this).find('input[name^=quarter]').attr('name', 'quarter_'+i);
                // $(this).find('input[name^=month]').attr('name', 'month_'+i);
                // $(this).find('input[name^=explain]').attr('name', 'explain_'+i);
                // $(this).find('input[name^=explainValue]').attr('name', 'explainValue_'+i);
                $(this).find('input.spec-type').attr('name', 'specType_'+i);
                $(this).find('input.quarter').attr('name', 'quarter_'+i);
                $(this).find('input.month').attr('name', 'month_'+i);
                $(this).find('input.explain').attr('name', 'explain_'+i);
                $(this).find('input.explain-value').attr('name', 'explainValue_'+i);
            });
        });
    };


    return {
        init: function() {
            initTable();
            initDetail();

            this.onEvent();
        },

        onEvent: function() {

            // 选择成员
            $('.select-member').on('click', function(){
                viewMember();
            });

            $('.city, .xian, .town, .village').on('change', function(){
                $('input[name=memberId]').val('');
                $('.select-member').empty().html('请选择');
            });


            // 模板下载
            $('#download_template').on('click', function(){
                var url = $(this).data('url');
                if(ADMININFO.type == 0) {
                    var cityId = $('#searchForm').find('input[name=cityId]').val();
                    var xianId = $('#searchForm').find('input[name=xianId]').val();
                    var townId = $('#searchForm').find('input[name=townId]').val();
                    var villageId = $('#searchForm').find('input[name=villageId]').val();
                } else {
                    var cityId = ADMININFO.cityId;
                    var xianId = ADMININFO.xianId;
                    var townId = ADMININFO.townId;
                    var villageId = ADMININFO.villageId;
                }
                if(!townId || townId == 0){
                    layer.msg('请选择镇');
                    return false;
                }
                var ledgerId = $('input[name=ledgerId]').val();

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="cityId" value="'+cityId+'" >';
                $form += '<input name="xianId" value="'+xianId+'" >';
                $form += '<input name="townId" value="'+townId+'" >';
                $form += '<input name="villageId" value="'+villageId+'" >';
                $form += '<input name="ledgerId" value="'+ledgerId+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });

            // 批量导入
            $('#import_csv').on('click', function(){
                var csv_file = $('input[name=csv_file]').val();
                var point = csv_file.lastIndexOf(".");

                var type = csv_file.substr(point);
                type = type.toLowerCase();
                if(type != ".csv" && type != ".xls" && type != ".xlsx"){
                    layer.msg('请选择csv, xls, xlsx文件');
                    return false;
                }

                var url = $('#import_form').attr('action');
                var data = new FormData();
                var csv_file = document.getElementById('csv_file').files[0];
                data.append('csv_file', csv_file);

                layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    //dataType : 'json',
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        layer.closeAll('loading'); // 关闭loading
                        layer.msg(data.msg);
                        if(data.status == 1){
                            window.location.reload();
                        }
                    }
                });
                return false;
            });

            // 批量导出
            $('#export_csv').on('click', function(){
                var url = $(this).data('url');
                if(ADMININFO.type == 0) {
                    var cityId = $('#searchForm').find('input[name=cityId]').val();
                    var xianId = $('#searchForm').find('input[name=xianId]').val();
                    var townId = $('#searchForm').find('input[name=townId]').val();
                    var villageId = $('#searchForm').find('input[name=villageId]').val();
                } else {
                    var cityId = ADMININFO.cityId;
                    var xianId = ADMININFO.xianId;
                    var townId = ADMININFO.townId;
                    var villageId = ADMININFO.villageId;
                }
                var ledgerId = $('input[name=ledgerId]').val();

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="cityId" value="'+cityId+'" >';
                $form += '<input name="xianId" value="'+xianId+'" >';
                $form += '<input name="townId" value="'+townId+'" >';
                $form += '<input name="villageId" value="'+villageId+'" >';
                $form += '<input name="ledgerId" value="'+ledgerId+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });


            // 表单提交
            $('#form-submit').on('click', function(){
                var form = this.form;
                var _this = $(this);

                if(!form.id.value) {
                    if(form.townId.value == 0) {
                        layer.msg('请选择所在地');
                        return;
                    }
                }
                if(form.memberId.value.trim() == '') {
                    layer.msg('请选择家庭成员');
                    return;
                }

                var is_valid_explain = true;
                var explain_msg = '';
                var explain_elm = '';
                var price_reg = /^(([0-9]+[\.]?[0-9]+)|[1-9])$/;
                var price_reg2 = /^\d+(\.\d{1,2})?$/;
                $('.policySpec-div').each(function(){
                    var explain = $(this).find('.explain-div').children().val();

                    explain_elm = $(this).find('.explain-value');
                    if (explain == 1) {
                        var amount = explain_elm.val();
                        if (amount.trim() == '') {
                            // is_valid_explain = false;
                            // explain_msg = '请输入金额';
                            // return false; // 跳出循环
                        } else {
                            if(!price_reg.test(amount)){
                                is_valid_explain = false;
                                explain_msg = '金额格式不正确';
                                return false;
                            }
                            if(!price_reg2.test(amount)){
                                is_valid_explain = false;
                                explain_msg = '金额小数点后只有两位';
                                return false;
                            }
                        }
                    } else {
                        var text = explain_elm.val();
                        if (text.trim() == '') {
                            // is_valid_explain = false;
                            // explain_msg = '请输入说明';
                            // return false;
                        } else {
                            if(text.length > 40){
                                is_valid_explain = false;
                                explain_msg = '说明最多为40个字符';
                                return false;
                            }
                        }
                    }
                });
                if(!is_valid_explain){
                    layer.msg(explain_msg);
                    explain_elm.focus();
                    return;
                }

                var isRemark = $('input[name=remark]').attr('data-required');
                if(isRemark == 1){
                    if(form.remark.value.trim() == '') {
                        layer.msg('请输入备注');
                        form.remark.focus();
                        return;
                    }
                    if(form.remark.value.length > 40){
                        layer.msg('备注最多为80个字符');
                        form.remark.focus();
                        return false;
                    }
                }

                var _data = $(form).serializeObject();
                _this.prop("disabled", true);

                $.ajax({
                    url : save_url,
                    type : 'post',
                    dataType : 'json',
                    contentType : "application/json; charset=utf-8",
                    data : JSON.stringify(_data),
                }).done(function(data) {
                    _this.prop("disabled", false);
                    if (data.code == 1) {
                        layer.msg('保存成功');
                        window.location.href = data.url;
                    } else {
                        layer.msg(data.msg);
                    }
                });
            });
        }

    };

}();

jQuery(document).ready(function() {
    Povertypolicy.init();

});
